const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const request = require("request");
import * as config from "../../config";

// import m from "../models/User";
import _ from "lodash";
import { Request, Response } from "express";
import { NextFunction } from "express-serve-static-core";
import efetch from "../efetch";
import r from "../r";

router.get("/tv/config/:symbol", async function(
  req: Request,
  res: Response,
  next: NextFunction
) {
  res.json({
    code: 200,
    data: {
      supports_marks: false,
      supports_time: true,
      exchanges: [
        { name: "All Exchanges", value: "", desc: "" },
        { name: "NasdaqNM", value: "NasdaqNM", desc: "NasdaqNM" },
        { name: "NYSE", value: "NYSE", desc: "NYSE" },
        { name: "NGM", value: "NGM", desc: "NGM" },
        { name: "NCM", value: "NCM", desc: "NCM" }
      ],
      supports_search: true,
      supports_group_request: false,
      supported_resolutions: [
        "1",
        "5",
        "10",
        "15",
        "30",
        "60",
        "240",
        "D",
        "W"
        // "M"
      ],
      symbols_types: [
        { name: "All types", value: "" },
        { name: "Stock", value: "stock" },
        { name: "Index", value: "index" }
      ],
      supports_timescale_marks: false
    },
    msg: "获取成功"
  });
});

router.get("/tv/getServerTime/:symbol", async function(
  req: Request,
  res: Response,
  next: NextFunction
) {
  res.json({
    code: 200,
    data: Number((new Date().getTime() / 1000).toFixed(0)),
    msg: "获取成功"
  });
});

router.get("/tv/symbolInfo/:symbol", async function(
  req: Request,
  res: Response,
  next: NextFunction
) {
  const { symbol } = req.query;
  res.json({
    code: 200,
    data: {
      has_daily: true,
      ticker: symbol,
      has_weekly_and_monthly: true,
      minmov2: 0,
      timezone: "GMT",
      session: "24x7",
      has_intraday: true,
      // 这里本来币之间带 斜杠的
      description: symbol,
      supported_resolutions: [
        "1",
        "5",
        "10",
        "15",
        "30",
        "60",
        "240",
        "D",
        "W",
        "M"
      ],
      type: "stock",
      intraday_multipliers: [
        "1",
        "5",
        "10",
        "15",
        "30",
        "60",
        "240",
        "D",
        "W",
        "M"
      ],
      volume_precision: 4,
      pointvalue: 1,
      has_empty_bars: true,
      name: symbol,
      minmov: 1,
      pricescale: Math.pow(10, config.point),
      has_no_volume: false
    },
    msg: "获取成功"
  });
});

router.get("/tv/getBars/:symbol", async function(
  req: Request,
  res: Response,
  next: NextFunction
) {
  const { symbol, resolution, from, to, isFirst } = req.query;
  if (process.env.NODE_ENV === "eh") {
    const data = "dslkfjlskdjfsfd";
    res.json({
      code: 200,
      data,
      msg: "success"
    });
  }
  try {
    const newurl = `${config.api}/market/${symbol}/${resolution}`;
    const ret = await r(
      {
        method: "GET",
        url: newurl,
        qs: {
          begintime: from,
          endtime: to
        }
      },
      req,
      res
    );

    const jsonRet = JSON.parse(ret.body);

    if (!jsonRet.data) {
      jsonRet.data = {
        c: [],
        h: [],
        l: [],
        o: [],
        s: "ok",
        t: [],
        v: []
      };
    } else {
      let arr: Array<any> = [];

      jsonRet.data.t.slice().forEach((d: any, index: number) => {
        arr.push({
          c: jsonRet.data.c[index],
          h: jsonRet.data.h[index],
          l: jsonRet.data.l[index],
          o: jsonRet.data.o[index],
          s: jsonRet.data.s,
          t: jsonRet.data.t[index],
          v: jsonRet.data.v[index]
        });
      });

      arr = arr.slice().sort((pre: any, next: any) => {
        return pre.t - next.t;
      });

      jsonRet.data = {
        c: [],
        h: [],
        l: [],
        o: [],
        s: "ok",
        t: [],
        v: []
      };

      arr.slice().forEach((d: any) => {
        jsonRet.data.c.push(d.c);
        jsonRet.data.h.push(d.h);
        jsonRet.data.l.push(d.l);
        jsonRet.data.o.push(d.o);
        jsonRet.data.s = d.s;
        jsonRet.data.t.push(d.t);
        jsonRet.data.v.push(d.v);
      });
    }

    // 暂时写死 以后做分页 在改回来
    jsonRet.data.s = "ok";

    res.json(jsonRet);
  } catch (e) {
    res.json({
      code: -1,
      data: undefined,
      msg: e
    });
  }
  // const newurl = `https://api.szzc.io/quote/tv/getBars/${symbol}?symbol=${symbol}&resolution=${resolution}&from=${from}&to=${to}&isFirst=${true}`;
});
export default router;
